
import { CmdResult, PandasCmdResultType } from "@/models/PandasCmdModel";




import * as api from "@/api";

import DfStroe from "@/store/DfStore";
import PdCmdStore from "@/store/PandasCmdStore";
import { FilterList } from '@/models/DfFilters';


import DataLoadStore from "@/store/DataLoadStore";
import CodeBuilderStore from '@/store/CodeBuilderStore';
import PandasCmdStore from '@/store/PandasCmdStore';
import { GroupbyModel } from '@/models/GroupbyModel';
import CommandStore from '@/store/CommandStore';
import { TableHandle } from '@/models/TableHandleModel';


function initApp() {
    PandasCmdStore.Clear()
    CodeBuilderStore.Clear()
}

async function updateForPandasCmd(ret: CmdResult,
    afterSuccessFunc: () => void = () => { }) {
    switch (ret.type) {
        case PandasCmdResultType.Error:
            PdCmdStore.SetError(ret);
            await updateAllCommands()

            break;

        case PandasCmdResultType.Success:
            PdCmdStore.SetCorrect()
            DfStroe.setData(ret.table.fields, ret.table.data, ret.columnInfos)
            afterSuccessFunc()
            await updateAllCommands()
            break;

        default:
            break;
    }
}


export async function loadDataFromFile() {
    let dls = DataLoadStore.getStateReadonly()

    let ret = await api.uploadFile(dls.File, dls.Args)
    await updateForPandasCmd(ret)
    // initApp()

    await updateCodeStore()
}

export async function filterByPandasQeury(queryString: string) {

    let ret = await api.query(queryString)
    await updateForPandasCmd(ret, async () => {
        await updateCodeStore()
    })

}

export async function GroupByPandas(model: GroupbyModel) {

    let ret = await api.groupby(model)
    await updateForPandasCmd(ret, async () => {
        await updateCodeStore()
    })
}

export async function removeCmd(id: string) {
    let ret = await api.removeCmd(id)
    await updateForPandasCmd(ret, async () => {
        await updateCodeStore()
    })
}


export async function filterByTableHandle(filters: FilterList) {

    let ret = await api.uploadFilters(filters)
    updateForPandasCmd(ret)
}


export async function updateCodeStore() {
    let ret = await api.getPyCode()
    CodeBuilderStore.update(ret)
}



export async function updateAllCommands() {
    let ret = await api.getAllCmds()
    CommandStore.setData(ret)
}


export async function tableHandle(tableHandle: TableHandle) {
    let ret = await api.tableHandle(tableHandle)
    switch (ret.type) {
        case PandasCmdResultType.Error:
            PdCmdStore.SetError(ret);
            await updateAllCommands()
            break;

        case PandasCmdResultType.Success:
            PdCmdStore.SetCorrect()
            DfStroe.setData(null, ret.table.data, null)
            await updateAllCommands()
            await updateCodeStore()
            break;

        default:
            break;
    }
}